﻿using System;
using System.Reflection;
using Moki.Exceptions;

namespace Moki.Extensions
{
    internal static class ReflectionExtensions
    {
        #region Events

        internal static string GetEventName(this MethodInfo method)
        {
            if (method.Name.StartsWith("add_"))
                return method.Name.Substring(4);
            else if (method.Name.StartsWith("remove_"))
                return method.Name.Substring(7);
            else
                throw new ArgumentException("Argument is not a event method");
        }

        internal static bool IsEvent(this MethodInfo method)
        {
            return method.IsEventAdd() || method.IsEventRemove();
        }

        internal static bool IsEventAdd(this MethodInfo method)
        {
            return method.Name.StartsWith("add_");
        }

        internal static bool IsEventRemove(this MethodInfo method)
        {
            return method.Name.StartsWith("remove_");
        } 
        #endregion

        #region Properties

        internal static PropertyInfo ToProperty(this MethodInfo method, Type type)
        {
            return type.GetProperty(method.Name.Substring(method.Name.IndexOf('_') + 1));
        }

        internal static bool IsPropertyGet(this MethodInfo method)
        {
            return method.Name.StartsWith("get_");
        }

        internal static bool IsPropertySet(this MethodInfo method)
        {
            return method.Name.StartsWith("set_");
        } 
        #endregion

        #region Validate
        internal static void Validate(this MethodInfo method, string messageFormat)
        {
            if (!method.IsVirtual)
                throw new MemberTypeException(messageFormat);
        }

        internal static void Validate(this MethodInfo method)
        {
            if (!method.IsVirtual)
                throw new MemberTypeException(String.Format("Can't stub or verify non-virtual member {0}", method.Name));
        } 
        #endregion
    }
}
